/**
 * 宠物技能数
 */
let total = 0;
let height = 300;
/**
 * 内丹位置：顺时针方向分别为1、2、3、4
 */
let _location = null;
/**
 * 正在编辑的表格索引
 */
let editingId = null;
/**
 * 请求地址
 */
let requestUrl = null;
/**
 * 宠物装备ID
 */
let equipmentId = null;
/**
 * 选择重置的共鸣低级内丹
 */
let resonanceId = null;
/**
 * 空白图片的URL地址
 */
let url = "/images/blank.png";

let data = {};

/**
 * 宠物技能认证状态
 */
let authStatus = ["未认证", "已认证"]
/**
 * 宠物资质类型数组
 */
let typeArray = ["野生", "宝宝", "变异"];
/**
 * 宠物装备类型
 */
let selectorArray = [null, "#hw", "#xq", "#kj"];
/**
 * 宠物技能类型
 */
let skillTypes = [null, "低级技能", "高级技能", "特殊技能"];
/**
 * 内丹操作
 * @type {string[]}
 */
let improveArray = ["&emsp;&emsp;提&ensp;升&emsp;&emsp;", "&ensp;增加共鸣&ensp;", "&ensp;重置共鸣&ensp;"]
/**
 * 宠物装备操作
 */
let operationArray = ["&emsp;&emsp;穿戴&emsp;&emsp;", "&emsp;&emsp;取下&emsp;&emsp;"];

/**
 * 宠物装备类型
 */
let equipmentTypes = [{
	type: 0,
	name: "无",
	selector: "#"
},{
	type: 1,
	name: "护腕",
	selector: "#hw"
}, {
	type: 2,
	name: "项圈",
	selector: "#xq"
}, {
	type: 3,
	name: "铠甲",
	selector: "#kj"
}];

function addHandler() {
	let roleId = $("#role_id").combobox("getValue");

	if (roleId) {
		$("#roleId").combobox("setValue", roleId);
	}

	$("#type").combobox("setValue", 1);

	requestUrl = "/chongwu/insert";

	$("#chongwu_dialog").dialog("open");
}

function editHandler() {
	let rowData = $("#chongwu_list").datagrid("getSelected");
	
	if (rowData) {
		requestUrl = "/chongwu/updateById";

		$("#id").val(rowData.id);
		$("#name").textbox("setValue", rowData.name);
		$("#roleId").combobox("setValue", rowData.roleId);
		$("#grade").numberspinner("setValue", rowData.grade);
		$("#score").numberspinner("setValue", rowData.score);
		$("#zizhiType").combobox("setValue", rowData.zizhiType);
		$("#categoryId").combobox("setValue", rowData.categoryId);
		$("#lifespan").numberspinner("setValue", rowData.lifespan);

		$("#chongwu_dialog").dialog("open");
	} else {
		alertMsg("请选择要修改的记录！", "warning");
	}
}

function deleteHandler() {
	let rowData = $("#chongwu_list").datagrid("getSelected");

	if (rowData) {
		$.messager.confirm("提示", "是否确认删除？", function(bool) {
			if (bool) {
				ajaxPost("/chongwu/deleteById", {
					id: rowData.id
				}, function(resp) {
					showMsg(resp.message);

					$("#chongwu_list").datagrid("reload");
				}, error);
			}
		});
	} else {
		alertMsg("请选择要删除的宠物！", "warning");
	}
}

function zizhiHandler() {
	let rowData = $("#chongwu_list").datagrid("getSelected");

	if (rowData) {
		let chongwuId = rowData.id;

		$("#chongwuId").val(chongwuId);

		ajaxGet("/chongwu_zizhi/selectByChongwuId", {
			chongwuId: chongwuId
		}, function(resp) {
			let data = resp.data;

			$("#gjzz").numberspinner("setValue", data.gjzz);
			$("#fyzz").numberspinner("setValue", data.fyzz);
			$("#tlzz").numberspinner("setValue", data.tlzz);
			$("#flzz").numberspinner("setValue", data.flzz);
			$("#sdzz").numberspinner("setValue", data.sdzz);
			$("#chengzhang").numberspinner("setValue", data.chengzhang);
		}, error);

		requestUrl = "/chongwu_zizhi/updateByChongwuId";

		$("#zizhi_dialog").dialog("open");
	} else {
		unselected();
	}
}

function attributeHandler() {
	let rowData = $("#chongwu_list").datagrid("getSelected");

	if (rowData) {
		ajaxGet("/chongwu_attribute/selectByChongwuId", {
			chongwuId: rowData.id
		}, function(resp) {
			let data = resp.data;

			if (data) {
				$("#attribute_id").val(data.id);

				$("#attribute_qixue").numberspinner("setValue", data.qixue);
				$("#attribute_mofa").numberspinner("setValue", data.mofa);
				$("#attribute_wlsh").numberspinner("setValue", data.wlsh);
				$("#attribute_fssh").numberspinner("setValue", data.fssh);
				$("#attribute_wlfy").numberspinner("setValue", data.wlfy);
				$("#attribute_fsfy").numberspinner("setValue", data.fsfy);
				$("#attribute_sudu").numberspinner("setValue", data.sudu);
				$("#attribute_dkfy").numberspinner("setValue", data.dkfy);
				$("#attribute_exp").numberspinner("setValue", data.exp);
			}
		}, error);

		requestUrl = "/chongwu_attribute/updateById";

		$("#attribute_dialog").dialog("open");
	} else {
		unselected();
	}
}

function skillHandler() {
	let rowData = $("#chongwu_list").datagrid("getSelected");

	if(rowData) {
		$("#skill_list").datagrid("reload", {
			chongwuId: rowData.id
		});

		$("#skill_dialog").dialog("open");
	} else {
		unselected();
	}
}

function computeHandler() {
	let rowData = $("#chongwu_list").datagrid("getSelected");

	if (rowData) {
		ajaxPost("/chongwu/compute", {
			chongwuId: rowData.id
		}, function(resp) {
			showMsg(resp.message);

			$("#chongwu_list").datagrid("reload");
		}, error);
	} else {
		unselected();
	}
}

function viewHandler() {
	let rowData = $("#chongwu_list").datagrid("getSelected");

	if (rowData) {
		$("#chongwu_datalist").datalist("reload", {
			callback: function () {
				$("#chongwu_datalist").datalist("selectRecord", rowData.id);
			}
		});

		$("#chongwu_detail").dialog("open");
	} else {
		unselected();
	}
}

/**
 * 加载宠物资质
 */
function loadZizhi() {
	let rowData = $("#chongwu_datalist").datalist("getSelected");

	if (rowData) {
		// 资质技能
		ajaxGet("/chongwu_zizhi/selectByChongwuId", {
			chongwuId: rowData.id
		}, function (resp) {
			let data = resp.data;

			let gjzz = data.gjzz;
			let fyzz = data.fyzz;
			let tlzz = data.tlzz;
			let flzz = data.flzz;
			let sdzz = data.sdzz;

			$("#chongwu_gjzz").progressbar("setValue", gjzz);
			$("#chongwu_fyzz").progressbar("setValue", fyzz);
			$("#chongwu_tlzz").progressbar("setValue", tlzz);
			$("#chongwu_flzz").progressbar("setValue", flzz);
			$("#chongwu_sdzz").progressbar("setValue", sdzz);
			// 成长显示为小数
			$("#chongwu_chengzhang").html((data.chengzhang / 1000).toFixed(3));

			// 查询对应宠物类型的初始资质
			ajaxGet("/chongwu_init_zizhi/selectList", {
				type: 1,
				chongwuId: rowData.categoryId
			}, function (resp) {
				let list = resp.data;

				if(list && list.length === 1) {
					let viewData = list[0];

					// 宠物普通资质上限
					$("#chongwu_gjzz").progressbar("setPercent", gjzz * 100 / viewData.gjzz);
					$("#chongwu_fyzz").progressbar("setPercent", fyzz * 100 / viewData.fyzz);
					$("#chongwu_tlzz").progressbar("setPercent", tlzz * 100 / viewData.tlzz);
					$("#chongwu_flzz").progressbar("setPercent", flzz * 100 / viewData.flzz);
					$("#chongwu_sdzz").progressbar("setPercent", sdzz * 100 / viewData.sdzz);

					// 宠物炼妖资质上限
					// $("#chongwu_gjzz").progressbar("setPercent", gjzz * 100 / Math.ceil(viewData.gjzz * 1.05));
					// $("#chongwu_fyzz").progressbar("setPercent", fyzz * 100 / Math.ceil(viewData.fyzz * 1.05));
					// $("#chongwu_tlzz").progressbar("setPercent", tlzz * 100 / Math.ceil(viewData.tlzz * 1.05));
					// $("#chongwu_flzz").progressbar("setPercent", flzz * 100 / Math.ceil(viewData.flzz * 1.05));
					// $("#chongwu_sdzz").progressbar("setPercent", sdzz * 100 / Math.ceil(viewData.sdzz * 1.05));
				}
			}, error);
		}, error);

		$("#chongwu_lifespan").html(rowData.lifespan);
	}
}

/**
 * 加载宠物技能
 */
function loadSkills() {
	total = 0;

	$("#chongwu_skills").empty();

	let rowData = $("#chongwu_datalist").datalist("getSelected");

	// 宠物技能
	ajaxGet("/chongwu_skill/getLearnedSkills", {
		chongwuId: rowData.id
	}, function(resp) {
		let data = resp.data;
		let chongwu_skills = "<tr>";

		if (data.length > 0) {
			for(let i = 0; i < data.length; i++) {
				let name = data[i].name;
				let type = data[i].type;
				let note = data[i].note;
				let image = data[i].image;
				let verifiable = data[i].verifiable;
				let authStatus = data[i].authStatus;

				chongwu_skills += "<td>";

				let title = name + "：" + note;

				// 不可认证的低级技能的边框为蓝色
				if(type === 1 && verifiable === 0) {
					chongwu_skills += "<div class='skill_box skill_blue' title='" + title + "'>";

					chongwu_skills += "<img src='" + image + "' />";
				} else {
					chongwu_skills += "<div class='skill_box skill_purple' title='" + title + "'>";

					chongwu_skills += "<img src='" + image + "' />";

					// 已认证
					if(authStatus === 1) {
						chongwu_skills += "<i></i>";
					}
				}

				chongwu_skills += "</div>";
				chongwu_skills += "</td>";

				total ++;

				if(total % 4 === 0) { // 4个技能1行
					chongwu_skills += "</tr><tr>";
				}
			}
		}

		// 通过宠物ID查询坐骑宠物
		ajaxGet("/zuoqi_skill/selectByChongwuId", {
			chongwuId: rowData.id
		}, function(resp) {
			let data = resp.data;

			if(rowData.tongyuStatus === 1 && data) {
				chongwu_skills += "<td>";
				chongwu_skills += 	"<div class='zuoqi_skill' title='" + data.name + "：" + data.note + "' >";
				chongwu_skills += 		"<img src='" + data.image + "' />";
				chongwu_skills += 	"</div>";
				chongwu_skills += "</td>";

				total ++;

				if(total % 4 === 0) { // 4个技能1行
					chongwu_skills += "</tr><tr>";
				}
			}

			ajaxGet("/chongwu_taozhuang_skill/selectByChongwuId", {
				chongwuId: rowData.id
			}, function(resp) {
				let data = resp.data;

				if(data) {
					chongwu_skills += 	"<td>";
					chongwu_skills += 		"<div class='taozhuang_skill_box' title='" + data.name + "：" + data.note + "' >";
					chongwu_skills += 			"<img height='58' src='" + data.image + "' />";
					chongwu_skills += 		"</div>";
					chongwu_skills += 	"</td>";
					chongwu_skills += "</tr>";
				}

				$("#chongwu_skills").append(chongwu_skills);
			}, error);
		}, error);
	},  error);
}

/**
 * 加载技能
 */
function lianyao_loadSkills() {
	count = 0;

	$("#yrz").hide();
	$("#wrz").hide();

	$("#lianyao_skills").empty();

	let rowData = $("#chongwu_datalist").datalist("getSelected");

	// 查询宠物已学习的技能
	ajaxGet("/chongwu_skill/getLearnedSkills", {
		chongwuId: rowData.id
	}, function(resp) {
		let data = resp.data;

		if (data.length > 0) {
			let chongwu_skills = "<tr>";

			for(let i = 0; i < data.length; i++) {
				let name = data[i].name;
				let type = data[i].type;
				let image = data[i].image;
				let verifiable = data[i].verifiable;
				let authStatus = data[i].authStatus;

				chongwu_skills += "<td>";

				if(type === 1 && verifiable === 0) {
					chongwu_skills += "<div class='skill_box skill_blue' title='" + name + "'>";

					chongwu_skills += "<img src='" + image + "' />";
				} else {
					chongwu_skills += "<div class='skill_box skill_purple' title='" + name + "'>";

					chongwu_skills += "<img src='" + image + "' />";

					if(authStatus === 1) {
						chongwu_skills += "<i></i>";
					}
				}

				chongwu_skills += "</div></td>";

				count ++;

				if(count > 0 && count % 4 === 0) { // 4个1行
					chongwu_skills += "</tr>";

					if (count !== data.length) {
						chongwu_skills += "<tr>";
					}
				}
			}

			$("#lianyao_skills").append(chongwu_skills);
		}
	}, error);

	ajaxGet("/chongwu_skill/hasAuthedSkills", {
		chongwuId: rowData.id
	}, function(resp) {
		if(resp.data === true) {
			$("#yrz").show();
		} else {
			$("#wrz").show();
		}
	}, error);
}

/**
 * 加载宠物内丹
 */
function loadNeidans() {
	let rowData = $("#chongwu_datalist").datalist("getSelected");

	$("#chongwu_id").val(rowData.id);

	for (let i = 1; i <= 4; i++) {
		$(".neidan_" + i + ">img").attr("src", "/images/lock.png");
	}
	$(".gaoji_neidan>img").attr("src", "/images/add.png");
	$(".zhuanshu_neidan>img").attr("src", "/images/add.png");

	// 根据当前宠物的造型为4个低级内丹格子动态绑定点击事件
	ajaxGet("/chongwu_category/selectById", {
		id: rowData.categoryId
	}, function (resp) {
		let data = resp.data;

		// 得到当前宠物造型可以学习的低级内丹数
		let count = data.neidanQuantity - 1;

		for (let i = 1; i <= count; i++) {
			$(".neidan_" + i + " > img").attr("src", "/images/add.png");

			$(".neidan_" + i).unbind("click").click(function() {
				_location = i;

				clickNeidan(1);
			});
		}

		// 如果小于4，则有内丹格子未解锁
		if (count < 4) {
			for (let i = count + 1; i <= 4; i++) {
				$(".neidan_" + i).unbind("click").click(function () {
					alertMsg("这只召唤灵只能学习" + count + "个低级内丹");
				});
			}
		}

		ajaxGet("/chongwu_neidan/selectNeidans", {
			chongwuId: rowData.id
		}, function (resp) {
			let list = resp.data;

			if (list && list.length > 0) {
				for (let i = 0; i < list.length; i++) {
					let neidan = list[i];
					let image = neidan.image;
					let location = neidan.location;

					if (neidan.type === 3) { // 专属内丹
						$(".zhuanshu_neidan > img").attr("src", image).attr("title", neidan.name);
					} else if (neidan.type === 2 || location === 0) { // 高级内丹
						$(".gaoji_neidan > img").attr("src", image).attr("title", neidan.name);
					} else { // 低级内丹
						$(".neidan_" + location + " > img").attr("src", image).attr("title", neidan.name);
					}
				}
			}
		}, error);
	}, error);
}

/**
 * 点击内丹
 * @param type 内丹类型 1-低级内丹；2-高级内丹；3-专属内丹；
 */
function clickNeidan(type) {
	let rowData = $("#chongwu_datalist").datalist("getSelected");

	if (rowData) {
		localStorage.setItem("mhxysy:chongwu_neidan:type", type);

		ajaxGet("/chongwu_neidan/selectList", {
			chongwuId: rowData.id,
			location: _location
		}, function (resp) {
			let data = resp.data;

			if (data.length > 0) {
				let neidanId = data[0].id;

				ajaxGet("/chongwu_neidan/selectDetails", {
					neidanId: neidanId
				}, function (resp) {
					let neidan = resp.data;

					$("#neidan_name").html(neidan.name);
					$("#neidan_grade").html(neidan.grade);
					$("#neidan_image").attr("src", neidan.image);
					$("#tip").html((neidan.grade >= 5) ? "（最高层）" : "");
					$("#neidan_note").html("本层内丹5层&emsp;&ensp;增加召唤灵12.64点法术伤害和126.4点气血。");

					// 5层的高级内丹
					if (type === 2 && neidan.grade >= 5) {

						ajaxGet("/chongwu_neidan/selectResonateCount", {
							neidanId: neidanId
						}, function (resp) {
							let count = resp.data;

							// 内丹共鸣数量上限，重置共鸣
							if (count >= 4) {
								$("#neidan_improve").linkbutton({
									text: improveArray[2]
								});
							} else {
								$("#neidan_improve").linkbutton({
									text: improveArray[1]
								});
							}
						}, error);


						selectResonates(neidanId);

						$("#resonate_neidans").show();
					} else {
						$("#resonate_neidans").hide();

						$("#neidan_improve").linkbutton({
							text: improveArray[0]
						});
					}

					$("#neidan_detail").dialog("open");
				}, error);
			} else {
				// 没有查询到宠物内丹，则打开学习内丹对话框
				let params = {
					type: type
				};

				if (type === 3) {
					params.chongwuId = rowData.categoryId;
				}

				$("#neidan_list").datalist("reload", params);

				$("#neidan_dialog").dialog("move", {
					left: 450
				}).dialog("open");
			}
		}, error);
	}
}

/**
 * 点击宠物装备格子
 * @param _this
 * @param type 宠物装备类型
 */
function clickEquipment(_this, type) {
	$("#hw").parent("div").css("border", "0");
	$("#xq").parent("div").css("border", "0");
	$("#kj").parent("div").css("border", "0");

	_this.parent("div").css("border", "1px blue solid");

	let chongwu = $("#chongwu_datalist").datalist("getSelected");

	if (chongwu) {
		let params = {
			chongwuId: chongwu.id,
			roleId: chongwu.roleId,
			type: type
		};

		equipmentId = _this.attr("ref");

		if (equipmentId) {
			params.callback = function () {
				$("#equipment_list").datalist("selectRecord", equipmentId);
			};

			$("#equipment_list").datalist("reload", params);
		} else {
			$("#equipment_list").datalist("reload", params);

			$("#equipment_dialog").dialog("open");
		}
	}
}

/**
 * 加载宠物装备
 */
function loadEquipments() {
	for (let i = 0; i < selectorArray.length; i++) {
		$(selectorArray[i]).attr("src", url).attr("ref", "");
	}

	let rowData = $("#chongwu_datalist").datalist("getSelected");

	/**
	 * 查询宠物已穿戴的宠物装备
	 */
	ajaxGet("/chongwu_equipment/getWeardEquipments", {
		chongwuId: rowData.id
	}, function(resp) {
		let list = resp.data;

		if(list.length > 0) {
			for(let i = 0; i < list.length; i++) {
				let data = list[i];
				let type = data.type;

				$(selectorArray[type]).attr({
					src: data.image,
					alt: data.name,
					ref: data.id
				});
			}
		}
	}, error);
}

function prepare() {
	// 宠物装备属性
	$("#property_white").empty();
	$("#property_green").empty().hide();
	$("#property_waiguan").empty().hide();
	$("#property_blue").empty().hide();
	// 星石属性
	$("#xingshi").hide();
	$("#property_xingshi_base").empty().hide();
	$("#property_xingshi_fuling").empty().hide();
	$("#property_xianghun").empty().hide();
}

/**
 * 查看宠物装备详情
 */
function viewEquipment(rowData) {
	prepare();

	// 宠物装备详情——基本信息
	ajaxGet("/chongwu_equipment_category/selectById", {
		id: rowData.categoryId
	}, function(resp) {
		let data = resp.data;

		$("#name_equipment").html(data.name);
		$("#note_equipment").html(data.note);
		$("#grade_equipment").html(data.grade);
		$("#image_equipment").attr("src", data.image);
		$("#type_equipment").html(equipmentTypes[data.type].name);
	}, error);

	// 查询宠物装备总评分
	ajaxGet("/chongwu_equipment/getTotalScore", {
		equipmentId: rowData.id
	}, function(resp) {
		$("#score_equipment").html(resp.data);
	}, error);

	// 查询宠物装备属性
	ajaxGet("/chongwu_equipment_attribute/selectAttributes", {
		equipmentId: rowData.id
	}, function(resp) {
		let data = resp.data;

		if(data.length > 0) {
			$("#property").show();

			for(let i = 0; i < data.length; i++) {
				let attribute = data[i];
				let property =  "&emsp;" + attribute.propertyName + "&ensp;+" + attribute.propertyValue;

				if (attribute.propertyType === 1) { // 1、基础属性
					// 只有一条基础属性
					$("#property_white").empty().append(property);
				} else if (attribute.propertyType === 2) { // 2、附加属性
					$("#property_green").append(property).show();
				} else if (attribute.propertyType === 3) { // 3、外观附加属性
					let html = "&emsp;外观追加&ensp;" + attribute.propertyName + "+" + attribute.propertyValue;

					// 只有一条外观追加属性
					$("#property_waiguan").empty().append(html).show();
				}
			}
		}
	}, error);

	// 查询宠物装备镶嵌的星石
	ajaxGet("/xingshi/selectByEquipmentId", {
		equipmentId: rowData.id
	}, function(resp) {
		let data = resp.data;

		if(data) {
			$("#xingshi").show();

			let xingshiId = data.id;

			/**
			 * 查询星石属性
			 */
			ajaxGet("/xingshi/selectAttribute", {
				xingshiId: xingshiId
			}, function(resp) {
				let attribute = resp.data;

				if (attribute) {
					let property = "&emsp;" + data.grade + "级" + attribute.name;

					property += "&ensp;" + attribute.propertyName + "&ensp;+" + attribute.propertyValue;

					$("#property_xingshi_base").append(property).show();
				}
			}, error);

			/**
			 * 查询星石的附灵信息
			 */
			ajaxGet("/xingshi_fuling/selectAttributes", {
				xingshiId: xingshiId
			}, function(resp) {
				let data = resp.data;

				if (data && data.length > 0) {
					let content = "";

					for (let i = 0; i < data.length; i++) {
						content += "&emsp;" + data[i].propertyName + "&ensp;+" + data[i].propertyValue;
					}

					$("#property_xingshi_fuling").append(content).show();
				}
			}, error);

			/**
			 * 查询星石的相魂属性
			 */
			ajaxGet("/xingshi_xianghun/selectByXingshiId", {
				xingshiId: xingshiId
			}, function(resp) {
				let data = resp.data;

				if(data) {
					$("#property_xingshi_xianghun").html("&emsp;" + data.effect).show();
				}
			}, error);
		}
	}, error);

	if(rowData.taozhuangId > 0 || rowData.waiguanId > 0) {
		$("#property_blue").show();

		if(rowData.taozhuangId > 0) {
			ajaxGet("/chongwu_taozhuang_category/selectById", {
				id: rowData.taozhuangId
			}, function(resp) {
				let data = resp.data;

				$("#property_blue").append("<div>&emsp;套装&ensp;" + data.name + "</div>");
			}, error);
		}
		if(rowData.waiguanId > 0) {
			ajaxGet("/chongwu_waiguan_category/selectById", {
				id: rowData.waiguanId
			}, function(resp) {
				let data = resp.data;

				$("#property_blue").append("<div>&emsp;外观&ensp;" + data.name + "</div>");
			}, error);
		}
	}

	$("#forger_equipment").html(rowData.forger);

	// 设置操作按钮的文本
	$("#wear").linkbutton({
		text: operationArray[rowData.wearStatus]
	});

	$("#equipment_detail").dialog("open");
}

/**
 * 查询共鸣的低级内丹列表
 */
function selectResonates(neidanId) {
	$("#neidans").empty();

	ajaxGet("/chongwu_neidan/selectResonates", {
		neidanId: neidanId
	}, function (resp) {
		let list = resp.data;

		if (list.length > 0) {
			let neidans = "";

			for (let i = 0; i < list.length; i++) {
				neidans += "共鸣：" + list[i] + "<br />";
			}

			$("#neidans").append(neidans);
		}
	}, error);
}

$(document).ready(function() {

	$("#role_id").combobox({
		url: "/role_account/selectAll",
		valueField: "id",
		textField: "name",
		width: 160,
		prompt: "-选择角色-",
		panelHeight: "auto",
		formatter: function(row) {
			ajaxGet("/role_category/selectById", {
				id: row.categoryId
			}, function(resp) {
				let data = resp.data;

				$("#modeling_" + row.id).attr("src", data.image);
			}, error);

			return "<img height='18' id='modeling_" + row.id + "' />&nbsp;" + row.name;
		}
	});

	$("#category_id").combobox({
		url: "/chongwu_category/selectAll",
		valueField: "id",
		textField: "name",
		width: 160,
		prompt: "-宠物类型-",
		panelHeight: "auto",
		formatter: function(row) {
			return "<img src='" + row.image + "' height='18' />&nbsp;" + row.name;
		}
	});

	$("#skill_ids").tagbox({
		url: "/chongwu_skill_category/selectAll",
		valueField: "id",
		textField: "name",
		width: 300,
		groupField: "type",
		panelHeight: "auto",
		prompt: "-选择技能-",
		groupFormatter: function(group) {
			return "<span class='red'>" + skillTypes[group] + "</span>";
		},
		formatter: function(row) {
			return "<img width='18' src='" + row.image + "' />&nbsp;" + row.name;
		}
	});

	$("#search").linkbutton({
		iconCls: "icon-search"
	}).click(function() {
		let categoryId = $("#category_id").combobox("getValue");
		let skillIds = $("#skill_ids").tagbox("getValues");
		let roleId = $("#role_id").combobox("getValue");

		$("#chongwu_list").datagrid("reload", {
			roleId: roleId,
			categoryId: categoryId,
			skillIds: JSON.stringify(skillIds)
		});
	});
	
	$("#clear").linkbutton({
		iconCls: "icon-delete"
	}).click(function() {
		$("#search_form").form("clear");
	});

	/******************************************************************************************************/

	/**
	 * chongwu_dialog
	 */

	$("#name").textbox({
		width: 120,
		required: true
	});
	
	$("#categoryId").combobox({
		url: "/chongwu_category/selectAll",
		valueField: "id",
		textField: "name",
		width: 120,
		required: true,
		panelHeight: "auto",
		formatter: function(row) {
			return "<img src='" + row.image + "' height='18' />&nbsp;" + row.name;
		},
		onSelect: function(record) {
			$("#name").textbox("setValue", record.name);
		}
	});
	
	$("#grade").numberspinner({
		min: 0,
		width: 120,
        editable: true,
        required: true
	});

	fetchSelect("#zizhiType", typeArray, {
		width: 120,
		required: true
	});

	$("#score").numberspinner({
		min: 0,
		width: 120,
        editable: true,
        required: true
	});
	
	$("#lifespan").numberspinner({
        min: 50,
        width: 120,
        editable: true,
        required: true
    });

	$("#roleId").combobox({
		url: "/role_account/selectAll",
		valueField: "id",
		textField: "name",
		width: 120,
		required: true,
		panelHeight: "auto",
		formatter: function(row) {
			ajaxGet("/role_category/selectById", {
				id: row.categoryId
			}, function(resp) {
				let data = resp.data;

				$("#role_" + row.id).attr("src", data.image);
			}, error);

			return "<img height='18' id='role_" + row.id + "' />&nbsp;" + row.name;
		},
		onSelect: function(record) {
			let grade = $("#grade").numberspinner("getValue");

			if(!grade) {
				$("#grade").numberspinner("setValue", record.grade + 10);
			}
		}
	});
	
	$("#chongwu_dialog").dialog({
		title: "宠物信息",
		width: 500,
		height: 300,
		buttons: [{
			iconCls: "icon-save",
			text: "保存",
			handler: function() {
				let selector = "#chongwu_form";

				checkForm(selector, function () {
					let data = $(selector).serialize();

					ajaxPost(requestUrl, data, function(resp) {
						showMsg(resp.message);

						$(selector).form("clear");
						$("#chongwu_dialog").dialog("close");
						$("#chongwu_list").datagrid("reload");
						$("#chongwu_datalist").datalist("reload");
					}, error);
				});
			}
		}, {
			iconCls: "icon-cancel",
			text: "取消",
			handler: function() {
				$("#chongwu_dialog").dialog("close");
				$("#chongwu_form").form("clear");
			}
		}]
	});

	/******************************************************************************************************/

	/**
	 * zizhi_dialog
	 */

	$("#gjzz").numberspinner({
		min: 0,
		width: 120,
		editable: true,
		required: true
	});

	$("#fyzz").numberspinner({
		min: 0,
		width: 120,
		editable: true,
		required: true
	});

	$("#tlzz").numberspinner({
		min: 0,
		width: 120,
		editable: true,
		required: true
	});

	$("#flzz").numberspinner({
		min: 0,
		width: 120,
		editable: true,
		required: true
	});

	$("#sdzz").numberspinner({
		min: 0,
		width: 120,
		editable: true,
		required: true
	});

	$("#chengzhang").numberspinner({
		min: 0,
		max: 1300,
		width: 120,
		required: true
	});

	$("#zizhi_dialog").dialog({
		title: "宠物资质",
		width: 500,
		height: 300,
		buttons: [{
			iconCls: "icon-save",
			text: "保存",
			handler: function() {
				let selector = "#zizhi_form";

				checkForm(selector, function () {
					let data = $(selector).serialize();

					ajaxPost(requestUrl, data, function(resp) {
						showMsg(resp.message);

						$(selector).form("clear");
						$("#zizhi_dialog").dialog("close");
						$("#chongwu_list").datagrid("reload");
					}, error);
				});
			}
		}, {
			iconCls: "icon-cancel",
			text: "取消",
			handler: function() {
				$("#zizhi_form").form("clear");
				$("#zizhi_dialog").dialog("close");
			}
		}]
	});

	/******************************************************************************************************/

	/**
	 * auth_dialog
	 */

	$("#auth_list").datalist({
		url: "/chongwu_skill/getCanAuthedSkills",
		valueField: "location",
		textField: "skillId",
		width: 200,
		height: height + 5,
		textFormatter: function(value, rowData, rowIndex) {
			ajaxGet("/chongwu_skill_category/selectById", {
				id: rowData.skillId
			}, function(resp) {
				let data = resp.data;

				$("#auth_skill_" + rowData.id).attr("src", data.image);
				$("#auth_name_" + rowData.id).html(data.name).css({
					"font-size": 20
				});
			}, error);

			return "<img height='30' id='auth_skill_" + rowData.id + "' />&nbsp;" +
				"<span id='auth_name_" + rowData.id + "'></span>";
		}
	});

	$("#auth_dialog").dialog({
		title: "技能认证",
		onClose: function() {
			let chongwu = $("#chongwu_list").datagrid("getSelected");

			if (chongwu) {
				$("#auth_list").datalist("reload", {
					chongwuId: chongwu.id
				});
			}
		},
		buttons: [{
			iconCls: "icon-ok",
			text: "确认",
			handler: function() {
				// 获取宠物即将认证的技能
				let chongwu_skill = $("#auth_list").datalist("getSelected");

				if(chongwu_skill) {
					let chongwu = $("#chongwu_list").datagrid("getSelected");

					if (chongwu) {
						ajaxPost("/chongwu_skill/authenticate", {
							chongwuId: chongwu.id,
							location: chongwu_skill.location
						}, function (resp) {
							showMsg(resp.message);
							lianyao_loadSkills();
							loadSkills();

							$("#auth_list").datalist("reload", {
								chongwuId: chongwu.id
							});

							$("#auth_dialog").dialog("close");
						}, error);
					}
				} else {
					// 认证技能为空，弹出提示
					alertMsg("请选择技能进行认证", "warning");
				}
			}
		}]
	});

	/******************************************************************************************************/

	/**
	 * chongwu_detail
	 */

	$("#chongwu_datalist").datalist({
		url: "/chongwu/selectAll",
		idField: "id",
		width: 190,
		height: 195,
		textFormatter: function(value, rowData, rowIndex) {
			ajaxGet("/chongwu_category/selectById", {
				id: rowData.categoryId
			}, function(res) {
				let data = res.data;

				$("#name_" +  rowIndex).html(rowData.name);
				$("#grade_" +  rowIndex).html(rowData.grade);
				$("#score_" +  rowIndex).html(rowData.score);
				$("#chongwu_category_" +  rowIndex).attr({
					src: data.image,
					title: data.name
				});
			}, error);

			let html = "";

			html += "<table>";
			html += 	"<tr>";
			html += 		"<td rowspan=2>";
			html += 			"<div style='border:1px black solid;width:54px;height:54px;'>";
			html +=					"<img width='52' id='chongwu_category_" +  rowIndex + "' />";
			html +=				"</div>";
			html += 		"</td>";
			html += 	"</tr>";

			html += 	"<tr>";
			html += 		"<td>";
			html += 			"<div>";
			html +=					"<div id='name_" +  rowIndex + "'></div>";
			html +=					"<span id='grade_" +  rowIndex + "'></span>" + "级<br/>";
			html +=					"评分：<span id='score_" +  rowIndex + "'></span>";
			html += 			"</div>";
			html += 		"</td>";
			html += 	"</tr>";
			html += "</table>";

			return html;
		},
		onSelect: function(rowIndex, rowData) {
			if (rowData) {
				// 左侧面板内容
				$("#chongwuName").html(rowData.name);
				$("#chongwuGrade").html(rowData.grade);

				ajaxGet("/chongwu_category/selectById", {
					id: rowData.categoryId
				}, function (resp) {
					let data = resp.data;

					$("#chongwu_img").prop("src", data.image);
				}, error);

				$("#chongwuScore").html(rowData.score);

				/*右侧面板内容*/
				// 属性装备
				ajaxGet("/chongwu_attribute/selectByChongwuId", {
					chongwuId: rowData.id
				}, function (resp) {
					let data = resp.data;

					// 设置气血、魔法、经验进度条的值
					$("#qixue").progressbar("setText", "{value}/" + data.qixue);
					$("#mofa").progressbar("setText", "{value}/" + data.mofa);

					$('#qixue').progressbar("setValue", data.qixue);
					$('#mofa').progressbar("setValue", data.mofa);

					// 查询宠物升级到下一级需要的经验
					ajaxGet("/grade_exp/selectChongwuExp", {
						grade: rowData.grade + 1
					}, function (resp) {
						let gradeExp = resp.data;

						$("#exp").progressbar("setValue", data.exp);

						if (gradeExp) {
							$("#exp").progressbar("setText", "{value}/" + gradeExp.exp);
							$("#exp").progressbar("setPercent", (data.exp / gradeExp.exp) * 100);
						}
					}, error);

					// 设置宠物属性
					$("#chongwu_wlsh").html(data.wlsh);
					$("#chongwu_wlfy").html(data.wlfy);
					$("#chongwu_fssh").html(data.fssh);
					$("#chongwu_fsfy").html(data.fsfy);
					$("#chongwu_sudu").html(data.sudu);
					$("#chongwu_dkfy").html(data.dkfy);
				}, error);

				// 加载宠物资质
				loadZizhi();

				// 加载宠物技能
				loadSkills();

				// 加载宠物内丹
				loadNeidans();

				// 加载宠物装备
				loadEquipments();
			}
		}
	});

	/**
	 * 气血
	 */
	$("#qixue").progressbar({
		width: 240,
		text: "{value}"
	}).progressbar("setColor", "red");

	/**
	 * 魔法
	 */
	$("#mofa").progressbar({
		width: 240,
		text: "{value}"
	}).progressbar("setColor", "blue");

	/**
	 * 经验
	 */
	$("#exp").progressbar({
		width: 200,
		text: "{value}"
	}).progressbar("setColor", "green");

	/**
	 * 攻击资质
	 */
	$("#chongwu_gjzz").progressbar({
		width: 90,
		text: "{value}"
	}).progressbar("setColor", "green");

	/**
	 * 防御资质
	 */
	$("#chongwu_fyzz").progressbar({
		width: 90,
		text: "{value}"
	}).progressbar("setColor", "green");

	/**
	 * 体力资质
	 */
	$("#chongwu_tlzz").progressbar({
		width: 90,
		text: "{value}"
	}).progressbar("setColor", "green");

	/**
	 * 法力资质
	 */
	$("#chongwu_flzz").progressbar({
		width: 90,
		text: "{value}"
	}).progressbar("setColor", "green");

	/**
	 * 速度资质
	 */
	$("#chongwu_sdzz").progressbar({
		width: 90,
		text: "{value}"
	}).progressbar("setColor", "green");

	$("#tabs").tabs({
		fit: true,
		pill: true,
		border: false,
		narrow: false,
		justified: true,
		closable: false,
		showHeader: true
	});

	$("#skill_panel").panel({
		fit: true
	});

	$(".gaoji_neidan > img").on("click", function() {
		_location = 0;

		clickNeidan(2);
	});

	/**
	 * 点击宠物装备
	 */
	for (let i = 1; i < equipmentTypes.length; i++) {
		let equipmentType = equipmentTypes[i];

		$(equipmentType.selector).on("click", function() {
			clickEquipment($(equipmentType.selector), equipmentType.type);
		}).attr("title", equipmentType.name);
	}

	/**
	 * 宠物详情对话框-【加点】按钮
	 */
	$("#jiadian").linkbutton({
		text: "&ensp;加点&ensp;"
	}).click(function() {
		let chongwu = $("#chongwu_datalist").datalist("getSelected");

		if (chongwu) {
			let chongwuId = chongwu.id;

			$("#chongwu_id").combobox("setValue", chongwuId);

			let $jiadian_schema = $("#jiadian_schema");

			$jiadian_schema.combobox("reload", {
				chongwuId: chongwuId
			});

			let jiadian_schemas = $jiadian_schema.combobox("getData");

			$jiadian_schema.combobox("select", jiadian_schemas[0].id);

			ajaxGet("/chongwu_jiadian/selectJiadian", {
				chongwuId: chongwuId,
				jiadianSchema: 1
			}, function(resp) {
				let data = resp.data;

				$("#jiadian_moli").numberspinner("setValue", data.moli);
				$("#jiadian_naili").numberspinner("setValue", data.naili);
				$("#jiadian_tizhi").numberspinner("setValue", data.tizhi);
				$("#jiadian_minjie").numberspinner("setValue", data.minjie);
				$("#jiadian_liliang").numberspinner("setValue", data.liliang);
			}, error);

			ajaxGet("/chongwu_attribute/selectByChongwuId", {
				chongwuId: chongwuId
			}, function(resp) {
				let data = resp.data;

				$("#jiadian_qixue").numberspinner("setValue", data.qixue);
				$("#jiadian_mofa").numberspinner("setValue", data.mofa);
				$("#jiadian_wlsh").numberspinner("setValue", data.wlsh);
				$("#jiadian_fssh").numberspinner("setValue", data.fssh);
				$("#jiadian_wlfy").numberspinner("setValue", data.wlfy);
				$("#jiadian_fsfy").numberspinner("setValue", data.fsfy);
				$("#jiadian_sudu").numberspinner("setValue", data.sudu);
			}, error);

			$("#jiadian_dialog").dialog("open");
		} else {
			unselected();
		}
	});

	/**
	 * 宠物详情对话框-【炼妖】按钮
	 */
	$("#lianyao").linkbutton({
		text: "&ensp;炼妖&ensp;"
	}).click(function() {
		let rowData = $("#chongwu_datalist").datalist("getSelected");

		if (rowData) {
			// 左侧面板内容
			$("#lianyao_chongwuname").html(rowData.name);
			$("#lianyao_chongwugrade").html(rowData.grade);
			$("#lianyao_chongwuscore").html(rowData.score);

			ajaxGet("/chongwu_category/selectById", {
				id: rowData.categoryId
			}, function (resp) {
				let data = resp.data;

				$("#lianyao_chongwuimage").prop("src", data.image);
			}, error);

			lianyao_loadSkills();

			$("#lianyao_dialog").dialog("open");
		}
	});

	/**
	 * 宠物详情对话框-【培养】按钮
	 */
	$("#peiyang").linkbutton({
		text: "&ensp;培养&ensp;"
	}).click(function() {
		unopen();
	});

	/**
	 * 宠物详情对话框-【休息】按钮
	 */
	$("#xiuxi").linkbutton({
		text: "&ensp;休息&ensp;"
	}).click(function() {
		unopen();
	});

	/**
	 * 宠物详情对话框
	 */
	$("#chongwu_detail").dialog({
		title: "宠物详情"
	});

	/******************************************************************************************************/

	/**
	 * lianyao_dialog
	 */

	/**
	 * 点击【认证替换】按钮
	 */
	$("#replace_auth").on("click", function() {
		let rowData = $("#chongwu_datalist").datalist("getSelected");

		if (rowData) {
			$("#replaceauth_list").datalist("reload", {
				chongwuId: rowData.id
			});

			$("#replaceauth_dialog").dialog("open");
		} else {
			alertMsg("请选择要修改的记录");
		}
	});

	/**
	 * 点击【认证取消】按钮
	 */
	$("#cancel_auth").on("click", function() {
		let rowData = $("#chongwu_datalist").datalist("getSelected");

		if (rowData) {
			$("#tabs").tabs("select", "资质技能");

			ajaxGet("/chongwu_skill/getAuthenticationMessage", {
				chongwuId: rowData.id
			}, function (resp) {
				$.messager.confirm("提示", resp.message, function (bool) {
					if (bool) {
						ajaxPost("/chongwu_skill/cancelAuth", {
							chongwuId: rowData.id
						}, function (resp) {
							showMsg(resp.message);

							loadSkills();
							lianyao_loadSkills();
						}, error);
					}
				});
			}, error);
		}
	});

	/**
	 * 点击【法术认证】按钮
	 */
	$("#authenticate").on("click", function() {
		let rowData = $("#chongwu_datalist").datalist("getSelected");

		if (rowData) {
			let chongwuId = rowData.id;

			ajaxPost("/chongwu_skill/validate", {
				chongwuId: chongwuId
			}, function () {
				requestUrl = "/chongwu_skill/authenticate";

				$("#tabs").tabs("select", "资质技能");
				$("#auth_list").datalist("reload", {
					chongwuId: chongwuId
				});
				$("#auth_dialog").dialog("open");
			}, error);
		}
	});

	/**
	 * 点击学技能的（+）
	 */
	$("#selected_skill").on("click", function() {
		let chongwu = $("#chongwu_list").datagrid("getSelected");

		if (chongwu) {
			$("#study_dialog").dialog("open");
		}
	});

	/**
	 * 宠物炼妖对话框的【学习】按钮
	 */
	$("#study").linkbutton({
		text: "&ensp;&ensp;学&ensp;习&ensp;&ensp;"
	}).click(function() {
		let chongwu = $("#chongwu_list").datagrid("getSelected");
		let chongwu_skill = $("#skill_datalist").datalist("getSelected");

		if(!chongwu) {
			alertMsg("请选择一只宠物！");
		} else if(!chongwu_skill) {
			alertMsg("请选择要学习的技能！");
		} else {
			ajaxPost("/chongwu_skill/study", {
				chongwuId: chongwu.id,
				skillId: chongwu_skill.id
			}, function(resp) {
				let message = "宠物<span class='green'>" + chongwu.name + "</span>"
					+ "学会了<span class='blue'>" + chongwu_skill.name + "</span>";

				// 只有替换技能时才提示遗忘了什么技能
				if (resp.message && resp.message === "replace") {
					message += "，同时遗忘了<span class='red'>" + resp.data + "</span>"
				}

				loadSkills();
				showMsg(message);
				lianyao_loadSkills();

				$("#skill_datalist").datalist("reload");
				$("#selected_skill").attr("src", "/images/add.png");
			}, error);
		}
	});

	/**
	 * 宠物炼妖对话框
	 */
	$("#lianyao_dialog").dialog({
		title: "宠物炼妖"
	});

	/******************************************************************************************************/

	/**
	 * replaceauth_dialog
	 */

	/**
	 * 替换认证对话框
	 */
	$("#replaceauth_list").datalist({
		url: "/chongwu_skill_category/getCanReplaceAuthSkills",
		valueField: "id",
		textField: "name",
		width: 160,
		height: height + 5,
		textFormatter: function(value, rowData, rowIndex) {
			return "<img width='30' src='" +  rowData.image + "' />"
				+ "<span style='font-size:25px;'>" + rowData.name + "</span>";
		}
	});

	/**
	 * 替换认证对话框的【确认】按钮
	 */
	$("#confirm").linkbutton({
		text: "&emsp;&emsp;确&emsp;定&emsp;&emsp;"
	}).on("click", function() {
		let chongwu = $("#chongwu_datalist").datalist("getSelected");

		if (chongwu) {
			let chongwu_skill = $("#replaceauth_list").datalist("getSelected");

			if (chongwu_skill) {
				ajaxPost("/chongwu_skill/replaceAuth", {
					chongwuId: chongwu.id,
					skillId: chongwu_skill.id
				}, function(resp) {
					loadSkills();
					lianyao_loadSkills();
					showMsg(resp.message);

					$("#replaceauth_form").form("clear");
					$("#replaceauth_dialog").dialog("close");
				}, error);
			} else {
				alertMsg("请选择替换技能");
			}
		} else {
			alertMsg("请选择要修改的记录");
		}
	});

	/**
	 * 替换认证对话框
	 */
	$("#replaceauth_dialog").dialog({
		title: "替换法术认证",
		modal: false
	});

	/******************************************************************************************************/

	/**
	 * jiadian_dialog
	 */

	$("#chongwu_id").combobox({
		url: "/chongwu/selectAll",
		valueField: "id",
		textField: "name",
		width: 180,
		height: 50,
		required: true,
		panelHeight: "auto",
		formatter: function (row) {
			let content = "<table>";

			content += "<tr>";
			content += "<td rowspan=2>";
			content += "<img height='50' id='chongwu_image_" + row.id + "' />";
			content += "</td>";
			content += "<td><span id='chongwu_name'>" + row.name + "</span></td>";
			content += "</tr>";
			content += "<tr>";
			content += "<td><span id='chongwu_grade'>" + row.grade + "</span>级</td>";
			content += "</tr>";
			content += "</table>";

			ajaxGet("/chongwu_category/selectById", {
				id: row.categoryId
			}, function(resp) {
				let data = resp.data;

				$("#chongwu_image_" + row.id).attr("src", data.image);
			}, error);

			return content;
		}
	});

	$("#jiadian_schema").combobox({
		url: "/jiadian_schema/selectByChongwuId",
		valueField: "id",
		textField: "name",
		width: 110,
		editable: false,
		panelHeight: "auto",
		onSelect: function(record) {
			let chongwu = $("#chongwu_list").datagrid("getSelected");

			if (chongwu) {
				let chongwuId = chongwu.id;
				let jiadianSchema = record.id;

				ajaxGet("/chongwu_jiadian/selectJiadian", {
					chongwuId: chongwuId,
					jiadianSchema: jiadianSchema
				}, function (resp) {
					let data = resp.data;

					if (data) {
						// 没有到解锁该加点方案
						if (data.unlockState === 0) {
							// 可以花费金币提前解锁第3、4套加点方案
							$.messager.confirm("提示", record.unlockTip, function (bool) {
								if (bool) {
									ajaxPost("/chongwu_jiadian/unlock", {
										chongwuId: chongwuId,
										jiadianSchema: jiadianSchema
									}, function (resp) {
										showMsg(resp.message);

										$("#jiadian_schema").combobox("reload", {})
											.combobox("setValue", jiadianSchema);
									}, function (response) {
										error(response);

										$("#jiadian_schema").combobox("setValue", 1);
									});
								}
							});
						} else {
							if (data.openState === 1) {
								$("#opened").linkbutton({
									text: "当前方案已开启"
								}).linkbutton("disable");
							} else {
								$("#opened").linkbutton({
									text: "&emsp;&emsp;开启&emsp;&emsp;"
								}).linkbutton("enable");
							}

							$("#tz").numberspinner("setValue", data.tizhi);
							$("#ml").numberspinner("setValue", data.moli);
							$("#ll").numberspinner("setValue", data.liliang);
							$("#nl").numberspinner("setValue", data.naili);
							$("#mj").numberspinner("setValue", data.minjie);

							ajaxGet("/chongwu_attribute/selectByChongwuId", {
								chongwuId: chongwuId
							}, function (resp) {
								let data = resp.data;

								$("#qx").numberspinner("setValue", data.qixue);
								$("#mf").numberspinner("setValue", data.mofa);
								$("#wlsh").numberspinner("setValue", data.wlsh);
								$("#fssh").numberspinner("setValue", data.fssh);
								$("#wlfy").numberspinner("setValue", data.wlfy);
								$("#fsfy").numberspinner("setValue", data.fsfy);
								$("#sd").numberspinner("setValue", data.sudu);
							}, error);
						}
					}
				}, error);
			}
		}
	});

	$("#edit").linkbutton({
		iconCls: "icon-edit"
	}).click(function () {
		let jiadianSchema = $("#jiadian_schema").combobox("getValue");

		if (jiadianSchema) {
			$.messager.prompt("改名", "输入新的加点方案名字（最多6个字）", function (value) {
				if (value) {
					let chongwu = $("#chongwu_list").datagrid("getSelected");

					if (chongwu) {
						let chongwuId = chongwu.id;

						ajaxPost("/chongwu_jiadian/rename", {
							name: value,
							chongwuId: chongwuId,
							jiadianSchema: jiadianSchema
						}, function (resp) {
							showMsg(resp.message);

							$("#jiadian_schema").combobox("reload", {
								chongwuId: chongwuId
							});
						}, error);
					}
				}
			});
		} else {
			alertMsg("请选择加点方案");
		}
	});

	$("#opened").linkbutton({
		text: "&emsp;&emsp;开启&emsp;&emsp;"
	}).click(function () {
		// 获取选择的加点方案
		let jiadianSchema = $("#jiadian_schema").combobox("getValue");
		let chongwu = $("#chongwu_list").datagrid("getSelected");

		if (jiadianSchema && chongwu) {
			let chongwuId = chongwu.id;

			// 通过宠物ID和加点方案查询角色加点
			ajaxGet("/chongwu_jiadian/selectJiadian", {
				chongwuId: chongwuId,
				jiadianSchema: jiadianSchema
			}, function (resp) {
				let data = resp.data;

				if (data && data.openState === 0) {
					// 开启加点
					ajaxPost("/chongwu_jiadian/enable", {
						chongwuId: chongwuId,
						jiadianSchema: jiadianSchema
					}, function (resp) {
						showMsg(resp.message);

						$("#opened").linkbutton({
							text: "当前方案已开启"
						}).linkbutton("disable");
					}, error);
				}
			}, error);
		}
	});

	$("#jiadian_qixue").numberspinner({
		min: 0,
		width: 100,
		editable: true,
		required: true
	});

	$("#jiadian_mofa").numberspinner({
		min: 0,
		width: 100,
		editable: true,
		required: true
	});

	$("#jiadian_wlsh").numberspinner({
		min: 0,
		width: 100,
		editable: true,
		required: true
	});

	$("#jiadian_fssh").numberspinner({
		min: 0,
		width: 100,
		editable: true,
		required: true
	});

	$("#jiadian_wlfy").numberspinner({
		min: 0,
		width: 100,
		editable: true,
		required: true
	});

	$("#jiadian_fsfy").numberspinner({
		min: 0,
		width: 100,
		editable: true,
		required: true
	});

	$("#jiadian_sudu").numberspinner({
		min: 0,
		width: 100,
		editable: true,
		required: true
	});

	$("#jiadian_tip").linkbutton({
		iconCls: "icon-help"
	}).click(function() {
		unopen();
	});

	$("#auto").linkbutton({
		text: "自动加点"
	}).click(function() {
		unopen();
	});

	$("#simulate").linkbutton({
		text: "属性模拟"
	}).click(function() {
		unopen();
	});

	$("#jiadian_tizhi").numberspinner({
		min: 0,
		width: 120,
		required: true
	});

	$("#jiadian_moli").numberspinner({
		min: 0,
		width: 120,
		required: true
	});

	$("#jiadian_liliang").numberspinner({
		min: 0,
		width: 120,
		required: true
	});

	$("#jiadian_naili").numberspinner({
		min: 0,
		width: 120,
		required: true
	});

	$("#jiadian_minjie").numberspinner({
		min: 0,
		width: 120,
		required: true
	});

	$("#save").linkbutton({
		text: "确认加点"
	}).click(function() {
		let chongwu = $("#chongwu_datalist").datalist("getSelected");

		if (chongwu) {
			let chongwuId = chongwu.id;

			$("#chongwu_id").val(chongwuId);
		}

		let selector = "#jiadian_form";

		checkForm(selector, function () {
			let data = $(selector).serialize();

			ajaxPost("/chongwu_jiadian/update", data, function(resp) {
				showMsg(resp.message);

				$(selector).form("clear");
				$("#jiadian_dialog").dialog("close");
			}, error);
		});
	});

	/**
	 * 宠物加点对话框
	 */
	$("#jiadian_dialog").dialog({
		title: "宠物加点"
	});

	/******************************************************************************************************/

	/**
	 * attribute_dialog
	 */

	$("#attribute_qixue").numberspinner({
		min: 0,
		required: true
	});

	$("#attribute_mofa").numberspinner({
		min: 0,
		required: true
	});

	$("#attribute_exp").numberspinner({
		min: 0,
		required: true
	});

	$("#attribute_wlsh").numberspinner({
		min: 0,
		required: true
	});

	$("#attribute_fssh").numberspinner({
		min: 0,
		required: true
	});

	$("#attribute_wlfy").numberspinner({
		min: 0,
		required: true
	});

	$("#attribute_fsfy").numberspinner({
		min: 0,
		required: true
	});

	$("#attribute_sudu").numberspinner({
		min: 0,
		required: true
	});

	$("#attribute_dkfy").numberspinner({
		min: 0,
		required: true
	});

	$("#attribute_dialog").dialog({
		title: "宠物属性",
		buttons: [{
			iconCls: "icon-save",
			text: "保存",
			handler: function() {
				let selector = "#attribute_form";

				checkForm(selector, function () {
					let data = $(selector).serialize();

					ajaxPost(requestUrl, data, function(resp) {
						showMsg(resp.message);

						$(selector).form("clear");
						$("#attribute_dialog").dialog("close");
					}, error);
				});
			}
		}, {
			iconCls: "icon-cancel",
			text: "取消",
			handler: function() {
				$("#attribute_form").form("clear");
				$("#attribute_dialog").dialog("close");
			}
		}]
	});

	/******************************************************************************************************/

	/**
	 * study_dialog
	 */

	$("#select").searchbox({
		width: 235,
		prompt: "输入技能名称",
		searcher: function(name) {
			$("#skill_datalist").datalist("reload", {
				name: name
			});
		}
	});

	$("#skill_datalist").datalist({
		url: "/chongwu_skill_category/selectByName",
		valueField: "id",
		textField: "name",
		width: 235,
		height: height + 2,
		textFormatter: function(value, rowData, rowIndex) {
			return "<img width='30' src='" +  rowData.image + "' />"
				+ "<span style='font-size:25px;'>" + rowData.name + "</span>";
		},
		onSelect: function(rowIndex, rowData) {
			if(rowData) {
				// 设置隐藏域的值
				$("#skillId").val(rowData.id);

				$("#selected_skill").attr("src", rowData.image);
			}
		}
	});

	$("#study_dialog").dialog({
		title: "选择技能书",
		modal: false
	});

	/******************************************************************************************************/

	/**
	 * neidan_detail
	 */
	/**
	 * 【遗忘】按钮
	 */
	$("#forget").linkbutton({
		text: "&emsp;&emsp;遗&emsp;忘&emsp;&emsp;"
	}).click(function() {
		let row = $("#chongwu_datalist").datalist("getSelected");

		if (row) {
			ajaxPost("/chongwu_neidan/forget", {
				chongwuId: row.id,
				location: _location
			}, function (resp) {
				loadNeidans();
				showMsg(resp.message);

				$("#forget_dialog").dialog("close");
			}, error);
		}
	});

	/**
	 * 【提升】按钮
	 */
	$("#neidan_improve").linkbutton({
		text: improveArray[0]
	}).click(function() {
		let chongwu = $("#chongwu_datalist").datalist("getSelected");

		if (chongwu) {
			ajaxGet("/chongwu_neidan/selectList", {
				chongwuId: chongwu.id,
				location: _location
			}, function (resp) {
				let list = resp.data;

				if (list && list.length > 0) {
					let data = list[0];

					if (data.grade >= 5) { // 内丹已经满级
						let type = localStorage.getItem("mhxysy:chongwu_neidan:type");

						// 高级内丹增加共鸣
						if (parseInt(type) === 2) {
							let neidanId = data.id;

							ajaxGet("/chongwu_neidan/selectResonateCount", {
								neidanId: neidanId
							}, function (resp) {
								let count = resp.data;

								// 内丹共鸣数量上限，重置共鸣
								if (count >= 4) {
									$("#reset_dialog").dialog("open");
								} else {
									/**
									 * 增加共鸣
									 */
									ajaxPost("/chongwu_neidan/resonate", {
										neidanId: neidanId
									}, function (resp) {
										showMsg(resp.message);

										selectResonates(neidanId);
									}, error);
								}
							}, error);
						} else {
							alertMsg("该内丹已达满层，不需要提升了");
						}
					} else if (data.comprehendStatus === 0) { // 内丹未领悟
						$("#wlw").dialog("open");
					} else {
						let grade = data.grade;

						ajaxGet("/chongwu_neidan_category/selectById", {
							id: data.neidanId
						}, function (resp) {
							let data = resp.data;
							let array = [0, 1, 1, 2, 4];

							$("#improve_name").html(data.name);
							$("#improve_name_").html(data.name);
							$("#improve_from").html(grade);
							$("#improve_to").html(grade + 1);
							$("#improve_effect").html(data.improveEffect);
							$("#improve_image").attr("src", data.image);
							$("#improve_count").html(array[grade]);

							$("#neidan_detail").dialog("close");
							$("#improve_dialog").dialog("open");
						}, error);
					}
				}
			}, error);
		}
	});

	$("#neidan_detail").dialog({
		title: " ",
		width: 250
	});

	/******************************************************************************************************/

	/**
	 * forget_dialog
	 */
	$("#neidan_forget").linkbutton({
		text: "&emsp;&emsp;遗&emsp;忘&emsp;&emsp;"
	}).click(function() {
		let row = $("#chongwu_datalist").datalist("getSelected");

		if (row) {
			ajaxGet("/chongwu_neidan/selectList", {
				chongwuId: row.id,
				location: _location
			}, function (resp) {
				let list = resp.data;

				if (list && list.length > 0) {
					let data = list[0];
					let grade = data.grade;

					$("#forget_grade").html(grade);

					get("/chongwu_neidan_category/selectById", {
						id: data.neidanId
					}, function (resp) {
						let data = resp.data;

						$("#forget_name").html(data.name);
						$("#forget_image").attr("src", data.image);

						if (grade === 1) {
							$("#eq1").show();
							$("#gt1").hide();
						} else {
							$("#after_forget_name").html(data.name);
							$("#after_forget_image").attr("src", data.image);
							$("#after_forget_grade").html(parseInt(grade / 2));

							$("#eq1").hide();
							$("#gt1").show();
						}

						$("#neidan_detail").dialog("close");
						$("#forget_dialog").dialog("open");
					}, error);
				}
			}, error);
		}
	});

	$("#cancel").linkbutton({
		text: "&emsp;&emsp;取&emsp;消&emsp;&emsp;"
	}).click(function() {
		$("#forget_dialog").dialog("close");
	});

	$("#forget_dialog").dialog({
		title: "遗忘内丹",
		width: 270,
		closed: true,
		closable: true,
		draggable: false
	});

	/******************************************************************************************************/

	/**
	 * improve_dialog
	 */
	$("#remove").linkbutton({
		text: "&emsp;&emsp;取&emsp;消&emsp;&emsp;"
	}).click(function() {
		$("#improve_dialog").dialog("close");
	});

	$("#improve").linkbutton({
		text: "&emsp;&emsp;提&emsp;升&emsp;&emsp;"
	}).on("click", function () {
		let chongwu = $("#chongwu_datalist").datalist("getSelected");

		if (chongwu) {
			ajaxPost("/chongwu_neidan/improve", {
				chongwuId: chongwu.id,
				location: _location
			}, function (resp) {
				loadNeidans();
				showMsg(resp.message);

				$("#improve_dialog").dialog("close");
			}, error);
		}
	});

	$("#improve_dialog").dialog({
		title: "提升内丹",
		width: 250
	});

	/******************************************************************************************************/

	/**
	 * reset_dialog
	 */
	$("#reset").linkbutton({
		text: "&emsp;重置共鸣&emsp;"
	}).on("click", function () {
		let data = $("#neidan_list").datalist("getSelected");

		if (data) {
			let neidanId = data.id;

			ajaxPost("/chongwu_neidan/resetResonate", {
				resonanceId: resonanceId,
				neidanId: neidanId
			}, function (resp) {
				showMsg(resp.message);

				selectResonates(neidanId);
			}, error);
		}
	});

	$("#reset_dialog").dialog({
		title: " ",
		width: 320
	});

	/******************************************************************************************************/

	/**
	 * equipment_dialog
	 */
	/**
	 * 宠物装备数据列表
	 */
	$("#equipment_list").datalist({
		url: "/chongwu_equipment/selectList",
		idField: "id",
		valueField: "id",
		textField: "id",
		width: 222,
		height: 310,
		textFormatter: function(value, rowData) {
			ajaxGet("/chongwu_equipment_category/selectById", {
				id: rowData.categoryId
			}, function(resp) {
				let data = resp.data;

				$("#equip_" + rowData.id).attr({
					"src": data.image,
					"title": data.name
				});
			}, error);

			ajaxGet("/chongwu_taozhuang_category/selectById", {
				id: rowData.taozhuangId
			}, function(resp) {
				let data = resp.data;

				$("#taozhuang_" + rowData.id).html(data.name);
			}, error);

			return "<table>" +
				"<tr>" +
				"<td rowspan='2'><img height='50' id='equip_" +  rowData.id + "' /></td>" +
				"<td>打造：<span>" + rowData.forger + "</span></td>" +
				"</tr>" +
				"<tr>" +
				"<td>套装：<span class='blue' id='taozhuang_" + rowData.id + "'></span></td>" +
				"</tr>" +
				"</table>";
		},
		onSelect: function(rowIndex, rowData) {
			viewEquipment(rowData);
		}
	});

	/**
	 * 宠物装备对话框
	 */
	$("#equipment_dialog").dialog({
		title: "宠物装备",
		onClose: function() {
			$("#equipment_detail").dialog("close");
		}
	});

	/******************************************************************************************************/

	/**
	 * 点击宠物装备详情对话框的【穿戴】/【取下】按钮
	 */
	$("#wear").linkbutton({
		text: "&emsp;&emsp;穿戴&emsp;&emsp;"
	}).click(function() {
		let chongwu = $("#chongwu_datalist").datalist("getSelected");

		if (chongwu) {
			if (!equipmentId) {
				let equipment = $("#equipment_list").datalist("getSelected");

				if (equipment) {
					equipmentId = equipment.id;
				} else {
					alert("请选择要穿戴的装备");
				}
			}

			ajaxPost("/chongwu_equipment/wear", {
				chongwuId: chongwu.id,
				equipmentId: equipmentId
			}, function(resp) {
				showMsg(resp.message);
				loadEquipments();

				$("#equipment_list").datagrid("reload").datagrid("unselectAll");
				$("#equipment_detail").dialog("close");
			}, error);
		}
	});

	/**
	 * 宠物装备详情对话框
	 */
	$("#equipment_detail").dialog({
		title: " ",
		width: 225,
		onClose: function () {
			prepare();
		}
	});

	/******************************************************************************************************/

	$("#abrogate").linkbutton({
		text: "&emsp;取&emsp;消&emsp;"
	}).click(function() {
		$("#wlw").dialog("close");
	});

	$("#comprehend").linkbutton({
		text: "&emsp;主动领悟&emsp;"
	}).on("click", function () {
		let row = $("#chongwu_datalist").datalist("getSelected");

		if (row) {
			ajaxPost("/chongwu_neidan/comprehend", {
				chongwuId: row.id,
				location: _location
			}, function (resp) {
				showMsg(resp.message);

				$("#wlw").dialog("close");
			}, error);
		}
	});

	$("#wlw").dialog({
		title: "尚未领悟",
		width: 360
	});

	$("#neidan_list").datalist({
		url: "/chongwu_neidan_category/selectList",
		idField: "id",
		valueField: "id",
		textField: "name",
		width: 180,
		height: 300,
		textFormatter: function(value, rowData, rowIndex) {
			return "<img width='30' src='" +  rowData.image + "' />"
				+ "<span style='font-size:25px;'>" + rowData.name + "</span>";
		}
	});

	$("#neidan_study").linkbutton({
		text: "&emsp;&emsp;学&emsp;习&emsp;&emsp;"
	}).click(function() {
		let row = $("#chongwu_datalist").datalist("getSelected");
		let rowData = $("#neidan_list").datalist("getSelected");

		if (rowData) {
			ajaxPost("/chongwu_neidan/study", {
				chongwuId: row.id,
				neidanId: rowData.id,
				location: _location
			}, function(resp) {
				loadNeidans();
				showMsg(resp.message);

				$("#neidan_form").form("clear");
				$("#neidan_dialog").dialog("close");
				$("#neidan_list").datagrid("reload");
			}, error);
		} else {
			alertMsg("请选择要学习的内丹。", "info");
		}
	});

	$("#neidan_dialog").dialog({
		title: "宠物内丹"
	});

	$(".zhuanshu_neidan > img").on("click", function () {
		let rowData = $("#chongwu_datalist").datalist("getSelected");

		if (rowData) {
			_location = 5;

			clickNeidan(3);
		}
	})
	
	/******************************************************************************************************/

	let pageList = [5, 10, 20, 40];

	$("#skill_list").datagrid({
		url: "/chongwu_skill/selectByPage",
		method: "get",
		width: 500,
		height: 300,
		pagination: true,
		pageList: pageList,
		pageSize: pageList[0],
		/**
		 * 结束行内编辑事件
		 * @param rowIndex 行号
		 * @param rowData 行数据
		 * @param changes 变更的行数据
		 */
		onAfterEdit: function (rowIndex, rowData, changes) {
			data = {
				id: rowData.id,
				chongwuId: rowData.chongwuId,
				skillId: changes.skillId ? changes.skillId : rowData.skillId,
				location: changes.location ? changes.location : rowData.location,
				authStatus: changes.authStatus ? changes.authStatus : rowData.authStatus
			};
		},
		toolbar: [{
			iconCls: "icon-add",
			text: "添加",
			handler: function() {
				let rowData = $("#chongwu_list").datagrid("getSelected");

				if(rowData) {
					let datagrid = $("#skill_list");

					datagrid.datagrid("appendRow",{
						id: null,
						skillId: null,
						location: null,
						authStatus: 0,
						chongwuId: rowData.id
					});

					// 得到表格数据总行数
					let total = datagrid.datagrid("getRows").length;

					editingId = total - 1;
					requestUrl = "/chongwu_skill/insert";

					datagrid.datagrid("beginEdit", editingId);
				} else {
					unselected();
				}
			}
		}, "-", {
			iconCls: "icon-edit",
			text: "修改",
			handler: function() {
				let datagrid = $("#skill_list");

				if (editingId != null) {
					confirmAction("上一次修改的数据未保存，是否现在保存？", function () {
						datagrid.datagrid("endEdit", editingId);
					}, function () {
						datagrid.datagrid("selectRow", editingId);
					});
				} else {
					let row = datagrid.datagrid("getSelected");

					if (row) {
						// 获取行索引，这个索引从0开始
						let rowIndex = datagrid.datagrid("getRowIndex", row);

						editingId = rowIndex;
						requestUrl = "/chongwu_skill/updateById";

						datagrid.datagrid("beginEdit", rowIndex);
					} else {
						unselected();
					}
				}
			}
		}, "-", {
			iconCls: "icon-save",
			text: "保存",
			handler: function() {
				if (editingId != null) {
					// 只有结束编辑才能获取到最新的值
					$("#skill_list").datagrid("endEdit", editingId);

					ajaxPost(requestUrl, data, function(resp) {
						editingId = null;

						showMsg(resp.message);

						$("#skill_list").datagrid("reload");
					}, error);
				}
			}
		}, "-", {
			iconCls: "icon-cancel",
			text: "取消",
			handler: function() {
				if (editingId != null) {
					$("#skill_list").datagrid("cancelEdit", editingId);

					editingId = null;
				}
			}
		}, "-", {
			iconCls: "icon-delete",
			text: "删除",
			handler: function() {
				let rowData = $("#chongwu_list").datagrid("getSelected");

				if(rowData) {
					$.messager.confirm("提示", "是否确认删除？", function(bool) {
						if (bool) {
							ajaxPost("/chongwu_skill/deleteById", {
								id: rowData.id
							}, function(resp) {
								showMsg(resp.message);

								$("#skill_list").datagrid("reload");
							}, error);
						}
					});
				} else {
					unselected();
				}
			}
		}],
		columns: [[
			{field: "id", hidden: true},
			{field: "chongwuId", hidden: true},
			{field: "skillId", title: "宠物技能", align: "center", width: 160
				, editor: {
					type: "combobox",
					options: {
						url: "/chongwu_skill_category/selectAll",
						valueField: "id",
						textField: "name",
						panelHeight: "auto"
					}
				}
				, formatter: function(value, rowData, rowIndex) {
					if (value) {
						ajaxGet("/chongwu_skill_category/selectById", {
							id: value
						}, function (resp) {
							let data = resp.data;

							$("#skill_" + rowIndex).attr({
								src: data.image,
								title: data.name
							});
						}, error);

						return "<img height='32' id='skill_" + rowIndex + "' />";
					}
				}
			},
			{field: "authStatus", title: "认证状态", align: "center", width: 160
				, editor: {
					type: "combobox",
					options: {
						data: getJsonData(authStatus),
						valueField: "value",
						textField: "text",
						panelHeight: "auto"
					}
				}
				, formatter: function(value) {
					return authStatus[value];
				}
			},
			{field: "location", title: "技能位置", align: "center", width: 160
				, editor: {
					type: "numberspinner",
					options: {
						min: 1,
						max: 13
					}
				}
			}
		]]
	});

	$("#skill_dialog").dialog({
		title: "宠物技能"
	});

	/******************************************************************************************************/

	/**
	 * 表格体的高度
	 * @type {number}
	 */
	let heigt_body = heigt_tr_with_role_details * 10;
	/**
	 * 包含角色详情列表格高度，不包含表格标题
	 * @type {number}
	 */
	let height_table = heigt_tool + heigt_header + heigt_body + heigt_footer + heigt_scoll_bar + 2;

	$("#chongwu_list").datagrid({
		url: "/chongwu/selectByPage",
		method: "get",
		height: height_table,
		fitColumns: true,
		rownumbers: true,
		pagination: true,
		onHeaderContextMenu: function(e) {
			e.preventDefault();

			if (!columnMenu){
				createColumnMenu("#chongwu_list");
			}
			columnMenu.menu("show", {
				left: e.pageX,
				top: e.pageY
			});
		},
		toolbar: [{
			iconCls: "icon-add",
			text: "添加",
			handler: function() {
				addHandler();
			}
		}, "-", {
			iconCls: "icon-edit",
			text: "修改",
			handler: function() {
				editHandler();
			}
		}, "-", {
			iconCls: "icon-delete",
			text: "删除",
			handler: function() {
				deleteHandler();
			}
		}, "-", {
			iconCls: "icon-shield",
			text: "设置资质",
			handler: function() {
				zizhiHandler();
			}
		}, "-", {
			iconCls: "icon-filter",
			text: "修改属性",
			handler: function() {
				attributeHandler();
			}
		}, "-", {
			iconCls: "icon-ok",
			text: "设置技能",
			handler: function() {
				skillHandler();
			}
		}, "-", {
			iconCls: "icon-reload",
			text: "计算评分",
			handler: function() {
				computeHandler();
			}
		}, "-", {
			iconCls: "icon-search",
			text: "预览宠物",
			handler: function() {
				viewHandler();
			}
		}],
		columns: [[
			{field: "id", hidden: true},
			{field: "name", title: "宠物名字", align: "center", width: 160},
			{field: "categoryId", title: "宠物类型", align: "center", width: 160
				, formatter: function(value, rowData, rowIndex) {
					ajaxGet("/chongwu_category/selectById", {
						id: value
					}, function(resp) {
						let data = resp.data;

						$("#chongwu_" + rowIndex).attr({
							src: data.image,
							title: data.name
						});
					}, error);
					
					return "<img height='" + size + "' id='chongwu_" + rowIndex + "' />";
				}
			},
			{field: "grade", title: "等级", align: "center", width: 160, sortable: true
				, formatter: function(value) {
					return "<span>" + value+ "级</span>";
				}
			},
			{field: "score", title: "评分", align: "center", width: 160, sortable: true},
			{field: "lifespan", title: "寿命", align: "center", width: 160, sortable: true
				, formatter: function(value) {
					if(value === 0) {
						return "<div>永生</div>";
					} else {
						return "<div>" + value + "</div>";
					}
				}
			},
			roleDetailsColumn
		]]
	});

});